package org.taskexecution.taskexecution.task;
import com.cephr.accountcenter.application.scheduledTask.TaskScheduleService;
import com.cephr.accountcenter.infrastructure.presistent.po.scheduledTask.TaskSchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
/**
 * @author Lydond
 * @description:
 * @create_date: 2025/10/20-16:12
 */


@Service
@Slf4j
public class TaskScanningService {

    @Autowired
    private TaskScheduleService TaskScheduleService; // <-- 注入您的 MP Service

    @Autowired
    private TaskExecutionService taskExecutionService;

    @Scheduled(cron = "0 0 * * * ?")
    public void scanAndExecuteTasks() {
        // 1. 拉取到期的任务 (调用您刚在 ServiceImpl 中添加的方法)
        List<TaskSchedule> dueTasks = TaskScheduleService.findDueTasks(LocalDateTime.now(), 100);

        log.info("扫描到期任务数量: " + dueTasks.size());

        for (TaskSchedule task : dueTasks) {
            try {
                // 2. 尝试获取锁 (调用您刚在 ServiceImpl 中添加的方法)
                boolean locked = TaskScheduleService.lockTask(task.getScheduleId());

                if (locked) {
                    // 3. 成功获取锁！ 异步执行
                    taskExecutionService.executeTask(task);
                }

            } catch (Exception e) {
                System.err.println("扫描任务时发生错误: " + task.getScheduleId() + e.getMessage());
            }
        }
    }
}